<?php
declare (strict_types = 1);

namespace app\controller\frontend;

use app\model\Inquiry;
use app\model\SysSetting;
use app\model\Website;
use app\service\EmailService;
use GuzzleHttp\Client;
use think\facade\Log;

class InquiryController extends BaseController
{
    /**
     * 保存新建的资源
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function save()
    {
        $param = request()->param();
        if(empty($param)){
            return jsonReturn(-1,'请填写询盘信息');
        }

        // 获取询盘收件箱
        $webSite = new Website();
        $site = $webSite->getWebsite(['domain' => $this->domain],['inquiryEmail'])['data']->toArray();
        $email = [];
        if(!empty($site['inquiryEmail'])){
            $email = array_column($site['inquiryEmail'],'email');
        }
        $inquiry = new Inquiry();
        $param['seller_id'] = $this->sellerId;
        $param['website_id'] = $this->siteId;
        $param['ip'] = request()->ip();
        $res = $inquiry -> addInquiry($param);
       try{
           // 获取suwork配置
           $sysSetting = new SysSetting();
           $setting = $sysSetting->getAllSysSetting([['title','like','suwork_%']])['data']->toArray();
           $key = array_column($setting,'title');
           $setting = array_combine($key,$setting);
           if(!empty($setting['suwork_appid']['value']) && !empty($setting['suwork_secret']['value']) && !empty($setting['suwork_api']['value'])){
               $suworkAccept = config('system.suwork_accept');
               $data = array_intersect_key($param,$suworkAccept);
               $data['referer_type'] = 1;
               $data['referer_web'] = empty($_SERVER['HTTP_REFERER']) ? '未知' : $_SERVER['HTTP_REFERER'];
               $data['appid'] =  $setting['suwork_appid']['value'];
               $data['secret'] = $setting['suwork_secret']['value'];
               $data['inquiry_time'] = date('Y-m-d H:i:s',time());
               $option = [
                   'form_params' => $data,
               ];
               $client = new Client();
               $response = $client->post($setting['suwork_api']['value'],$option);
               $result = json_decode($response->getBody()->getContents(),true);
               if($result['code'] != 0){
                   Log::record($result['msg'],'info');
               }
           }
           // 发送邮件
               $EmailService = new EmailService();
               $EmailService->sendEmail($this->domain.'网站收到询盘',$email);
       }catch (\Exception $e){
           Log::error($e->getMessage());
           return jsonReturn(0,'提交成功',1);
       }
        return json($res);
    }

}
